﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web;
using System.IO.Compression;

namespace Fly.Net
{
    public class HttpCompressModule : IHttpModule
    {        
        #region IHttpModule 成员

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.PostReleaseRequestState += new EventHandler(context_PostReleaseRequestState);
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

      
       
        void context_BeginRequest(object sender, EventArgs e)
        {
            var cacheControl = HttpContext.Current.Request.Headers["Cache-Control"];
            if (HttpContext.Current.Request.RequestType == "POST" || (cacheControl != null && cacheControl.ToLower() == "no-cache"))
            {
                if (NeedCompress && SmartCompressStream.CanCompressType != Net.CompressTypes.None)
                {
                    HttpUtils.EnableCompress();
                    //HttpContext.Current.Response.Filter = new SmartCompressStream(HttpContext.Current.Response.Filter);
                }
            }

        }

        void context_PostReleaseRequestState(object sender, EventArgs e)
        {
            if (NeedCompress && SmartCompressStream.CanCompressType != Net.CompressTypes.None)
            {
                HttpUtils.EnableCompress();
                //HttpContext.Current.Response.Filter = new SmartCompressStream(HttpContext.Current.Response.Filter);
            }
        }

        #endregion

        static string _compressTypes = null;
        public static string CompressTypes
        {
            get
            {
                if (_compressTypes == null)
                {
                    _compressTypes = System.Configuration.ConfigurationManager.AppSettings["Fly-CompressTypes"];
                    if (_compressTypes == null)
                        _compressTypes = "text/html,text/javascript,application/x-javascript,text/css,application/x-css,application/json";
                }
                return _compressTypes;
            }
        }

        /// <summary>
        /// 当前请求是否需要压缩
        /// </summary>
        public static bool NeedCompress
        {
            get
            {
                return CompressTypes.Contains(HttpContext.Current.Response.ContentType);
            }
        }
    }
}
